package com.lianyu.wangyiyun.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Looper;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Toast;

import com.lianyu.wangyiyun.R;
import com.lianyu.wangyiyun.databinding.ActivityLoginBinding;
import com.lianyu.wangyiyun.utils.LoginManager;
import com.lianyu.wangyiyun.utils.MyUtils;

import org.jetbrains.annotations.NotNull;

import java.util.Map;

import cn.leancloud.AVUser;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author Chen Yuguang
 */
public class LoginActivity extends BaseActivity {

    private ActivityLoginBinding activityLoginBinding;
    private boolean isVisible;

    @Override
    protected void initView() {
        activityLoginBinding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(activityLoginBinding.getRoot());
        boolean checked = LoginManager.getChecked();
        activityLoginBinding.checkBox.setChecked(checked);
        if (checked) {
            Map<String, String> m = LoginManager.readLogin();
            activityLoginBinding.editAccount.setText(m.get("account"));
            activityLoginBinding.editPassword.setText(m.get("password"));
        }
        activityLoginBinding.editPassword.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                // 此处为得到焦点时的处理内容
                activityLoginBinding.frameImage.setImageResource(R.drawable.frame_invisible);
                AnimationDrawable animationDrawable = (AnimationDrawable) activityLoginBinding.frameImage.getDrawable();
                animationDrawable.start();
            } else {
                // 此处为失去焦点时的处理内容
                activityLoginBinding.frameImage.setImageResource(R.drawable.frame_visible);
                AnimationDrawable animationDrawable = (AnimationDrawable) activityLoginBinding.frameImage.getDrawable();
                animationDrawable.start();
            }
        });

        activityLoginBinding.btnLogin.setOnClickListener(v -> {
            // 按钮动画
            MyUtils.btnAnimator(v);
            // 隐藏输入框
            activityLoginBinding.group.setVisibility(View.INVISIBLE);
            // 动画
            inputAnimator();
            // 禁止二次点击
            activityLoginBinding.btnSignUp.setClickable(false);
            v.setClickable(false);

            login();
        });

        activityLoginBinding.btnSignUp.setOnClickListener(v -> {
            // 按钮动画
            MyUtils.btnAnimator(v);
            // 隐藏输入框
            activityLoginBinding.group.setVisibility(View.INVISIBLE);
            // 输入框动画
            inputAnimator();
            // 禁止二次点击
            v.setClickable(false);
            activityLoginBinding.btnLogin.setClickable(false);

            signUp();
        });

        activityLoginBinding.visibility.setOnClickListener(v -> {
            isVisible = !isVisible;
            if (isVisible) {
                v.setSelected(true);
                //密码可见
                activityLoginBinding.editPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                v.setSelected(false);
                //密码不可见
                activityLoginBinding.editPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
        });

    }

    @Override
    protected void initEvent() {
        MyUtils.verifyStoragePermissions(this);
    }

    private void login(){
        String account = activityLoginBinding.editAccount.getText().toString();
        String password = activityLoginBinding.editPassword.getText().toString();
        // 判断账号或密码是否为空
        if (account.isEmpty() || password.isEmpty()) {
            Toast.makeText(LoginActivity.this, "账号或密码为空，请检查内容", Toast.LENGTH_LONG).show();
            recovery();
            return;
        }

        // 登录
        AVUser.logIn(account, password).subscribe(new Observer<AVUser>() {
            @Override
            public void onSubscribe(@NotNull Disposable disposable) {
            }

            @Override
            public void onNext(@NotNull AVUser user) {
                // 登录成功
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                LoginManager.configLoginInfo(activityLoginBinding.checkBox.isChecked(),account,password);
                new Handler(Looper.myLooper()).postDelayed(() -> {
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                    //跳转动画
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                },2000);

            }

            @Override
            public void onError(@NotNull Throwable throwable) {
                // 登录失败（可能是密码错误）
                recovery();
                Toast.makeText(LoginActivity.this, "登录失败，输入有误或网络出错", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void signUp(){
        String account = activityLoginBinding.editAccount.getText().toString();
        String password = activityLoginBinding.editPassword.getText().toString();
        // 判断账号或密码是否为空
        if (account.isEmpty() || password.isEmpty()) {
            Toast.makeText(LoginActivity.this, "账号或密码为空，请检查内容", Toast.LENGTH_LONG).show();
            recovery();
            return;
        }

        // 注册
        AVUser user = new AVUser();
        user.setUsername(account);
        user.setPassword(password);
        user.signUpInBackground().subscribe(new Observer<AVUser>() {
            @Override
            public void onSubscribe(@NotNull Disposable disposable) {
            }

            @Override
            public void onNext(@NotNull AVUser user) {
                // 注册成功
                Toast.makeText(LoginActivity.this, "注册成功", Toast.LENGTH_LONG).show();
                LoginManager.configLoginInfo(activityLoginBinding.checkBox.isChecked(),account,password);
            }

            @Override
            public void onError(@NotNull Throwable throwable) {
                // 注册失败
                recovery();
                Toast.makeText(LoginActivity.this, "注册失败，用户名已被使用或网络出错", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 输入框的动画效果
     */
    private void inputAnimator() {

        ObjectAnimator animator = ObjectAnimator.ofFloat(activityLoginBinding.inputLayout,
                "scaleX", 1f, 0.5f);
        animator.setDuration(1000);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.start();
        animator.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                /*
                 * 动画结束后，先显示加载的动画，然后再隐藏输入框
                 */
                activityLoginBinding.layoutProgress.setVisibility(View.VISIBLE);
                progressAnimator();
                activityLoginBinding.inputLayout.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }
        });

    }

    /**
     * 出现进度动画
     */
    private void progressAnimator() {
        PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("scaleX",
                0.5f, 1f);
        PropertyValuesHolder animator2 = PropertyValuesHolder.ofFloat("scaleY",
                0.5f, 1f);
        ObjectAnimator animator3 = ObjectAnimator.ofPropertyValuesHolder(activityLoginBinding.layoutProgress,
                animator, animator2);
        animator3.setDuration(1000);
        animator3.setInterpolator(new JellyInterpolator());
        animator3.start();
    }

    /**
     * 恢复初始状态
     */
    private void recovery() {
        new Handler(Looper.myLooper()).postDelayed(() -> {
            activityLoginBinding.layoutProgress.setVisibility(View.GONE);
            activityLoginBinding.inputLayout.setVisibility(View.VISIBLE);
            activityLoginBinding.group.setVisibility(View.VISIBLE);

            ObjectAnimator animator = ObjectAnimator.ofFloat(activityLoginBinding.inputLayout, "scaleX", 0.5f, 1f);
            animator.setDuration(500);
            animator.setInterpolator(new AccelerateDecelerateInterpolator());
            animator.start();
            animator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    //动画结束，恢复可点击
                    activityLoginBinding.btnLogin.setClickable(true);
                    activityLoginBinding.btnSignUp.setClickable(true);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        }, 2000);
    }

    public static class JellyInterpolator extends LinearInterpolator {
        private final float factor;

        public JellyInterpolator() {
            this.factor = 0.15f;
        }

        @Override
        public float getInterpolation(float input) {
            return (float) (Math.pow(2, -10 * input)
                    * Math.sin((input - factor / 4) * (2 * Math.PI) / factor) + 1);
        }
    }


}